package com.gl.doc.builder;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ZipUtil;
import com.gl.doc.model.Paragraph;
import com.gl.doc.model.Word;
import com.gl.doc.model.WordComment;
import com.gl.doc.model.container.WordXmlContainer;
import com.gl.doc.operation.WordContentRead;
import com.gl.doc.operation.WordOperation;
import com.gl.doc.path.TempPath;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.nio.charset.Charset;
import java.util.List;

/**
 * word文档对象
 */
@Data
@Slf4j
public class WordDocument {
    /**
     * word结构
     */
    protected Word word;
    /**
     * word操作
     */
    protected WordOperation wordOperation;
    /**
     * word内容读取
     */
    protected WordContentRead wordContentRead;
    /**
     * wordXml存储容器
     */
    protected WordXmlContainer wordXmlContainer;

    /**
     * 根据文件对象解析word结构
     *
     * @param file 文件对象
     */
    public void parseWord(File file) {
        word = wordOperation.parseWord(file);
    }

    /**
     * 根据文件对象解析word结构
     *
     * @param inputStream 输入流
     */
    public void parseWord(InputStream inputStream) {
        word = wordOperation.parseWord(inputStream);
    }

    /**
     * 添加批注
     *
     * @param wordComment 批注对象{@link WordComment}
     */
    public void addWordComment(WordComment wordComment) {
        wordOperation.addWordComment(wordComment, this);
    }

    /**
     * 获取word的所有段落
     *
     * @return word段落
     */
    public List<Paragraph> getParagraphs() {
        return wordContentRead.getParagraphs(this);
    }

    /**
     * 根据下标获取一段内容
     *
     * @param index 下标
     * @return word段落
     */
    public Paragraph getParagraph(Integer index) {
        return wordContentRead.getParagraph(this, index);
    }

    /**
     * 保存文件
     */
    public void save() {
        try (
                FileOutputStream fileOutputStream = new FileOutputStream(new File(word.getTempPath() + "/" + "xxx.docx"));
        ) {
            this.save(fileOutputStream);
        } catch (Exception e) {
            log.error("文件保存异常", e);
        }
    }

    /**
     * 保存文件
     *
     * @param outputStream 输出流
     */
    public void save(OutputStream outputStream) {
        try (
                BufferedOutputStream os = new BufferedOutputStream(outputStream);
        ) {
            File zipFile = ZipUtil.zip(word.getContextPath(), Charset.defaultCharset());
            os.write(FileUtil.readBytes(zipFile));
            os.flush();
        } catch (Exception e) {
            log.error("文件保存异常", e);
        } finally {
            TempPath.deleteTempPath(word.getTempPath());
        }
    }
}
